package com.neuronbit.businessflow.intellij.function;

import com.neuronbit.businessflow.intellij.editor.BpmHtmlFileEditor;
import com.neuronbit.businessflow.intellij.dialog.PsiFieldDialog;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.ui.jcef.JBCefJSQuery;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.PathNotFoundException;
import org.apache.commons.lang3.StringUtils;
import org.cef.browser.CefBrowser;
import org.jetbrains.annotations.NotNull;

import java.awt.*;
import java.util.function.Function;

/**
 * The type Param filter function.
 */
public class ParamFilterFunction implements Function<String, JBCefJSQuery.Response> {
    private final Project project;
    private final CefBrowser cefBrowser;
    private final String viewerUrl;

    /**
     * Instantiates a new Param filter function.
     *
     * @param project    the project
     * @param cefBrowser the cef browser
     * @param viewerUrl  the viewer url
     */
    public ParamFilterFunction(Project project, @NotNull CefBrowser cefBrowser, String viewerUrl) {
        this.project = project;
        this.cefBrowser = cefBrowser;
        this.viewerUrl = viewerUrl;
    }

    @Override
    public JBCefJSQuery.Response apply(String params) {
        Logger.getInstance(BpmHtmlFileEditor.class).info("message from browser " + params);

        EventQueue.invokeLater(() -> {
            PsiFieldDialog dialog = new PsiFieldDialog(project, params);
            dialog.show();
            String selected = dialog.getSelected();
            if (StringUtils.isNotBlank(selected)) {
                String fieldId = null;
                if (StringUtils.isNotBlank(params)) {

                    try {
                        fieldId = JsonPath.read(params, "$.fieldId");
                    } catch (PathNotFoundException e) {
                        //ignore
                    }
                }
                cefBrowser.executeJavaScript( // 6
                        """
                                window.AliLowCodeEngine.event.emit('ParamEvent', ['%s','%s']);
                                """.formatted(fieldId, selected),
                        viewerUrl, 0
                );
            }
        });
        return null;
    }
}
